package com.vancouver.knows.ui.fragment.homePage;

import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;

import com.pangu.AMApplication;
import com.pangu.bean.PageInfo;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.PullListItemBrowser;
import com.pangu.ui.refresh.ARefreshViewController;
import com.pangu.util.DeviceUtil;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.bean.DiscountCategoryInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.bean.WeatherInfo;
import com.vancouver.knows.business.task.mark.FetchCityDiscountsTaskMark;
import com.vancouver.knows.ui.activity.MainActivity;
import com.vancouver.knows.ui.activity.citydiscount.CityDiscountDetailActivity;
import com.vancouver.knows.ui.activity.citydiscount.CityDiscoutResultActivity;
import com.vancouver.knows.ui.activity.citynews.CityNewsDetailActivity;
import com.vancouver.knows.ui.activity.event.EventDetailActivity;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.HomePageInfo;
import com.vancouver.knows.business.service.impl.HomePageHandle;
import com.vancouver.knows.business.task.mark.HomePageTaskMark;
import com.vancouver.knows.ui.activity.userpost.UserPostActivity;
import com.vancouver.knows.ui.activity.userpost.UserPostDetailActivity;
import com.vancouver.knows.util.AppUtils;

public class HomepageAddHeadView extends PullListItemBrowser<AMApplication> {
	private Context mContext;
	private Activity activity;
	private LayoutInflater mInflater;
	private HomepageCarouselView viewPageView;
	//private HomepageNotLoginView mNotLoginView;
	//private HomepageAfterLoginView mAfterLoginView;
	private HomepageBreakNewsView mBreakNewsView;
	private HomepageCategoryGridView mCategoryGridView;
	private HomepageLiveFeedView mLiveFeedView;
	//private HomepageBusinessView mBusinessView;
	private BusinessModule bModule;
	private View mFooterView;

	private HomepageListener mHomepageListener;

	private String discountCategory = "";
	private String discountSubcategory = "";
	private int mTotalCount = 0;

	@SuppressWarnings("rawtypes")
	public HomepageAddHeadView(Context context, ARefreshViewController mController) {
		super(context, mController);
		mContext = context;
		mInflater = LayoutInflater.from(context);
		init();
	}

	private void init() {
		bModule = ((MainApplication) imContext).getBusinessModule();

	}

	@Override
	protected View createLoadingView(Context context) {
		RelativeLayout loadingView = (RelativeLayout) super.createLoadingView(context);
		LayoutParams linearLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		ImageView loadingImageView = new ImageView(context);
		loadingImageView.setLayoutParams(linearLayoutParams);
		loadingImageView.setImageResource(R.drawable.loading_home_page);
		loadingImageView.setScaleType(ImageView.ScaleType.FIT_XY);
		loadingView.addView(loadingImageView, 0);
		return loadingView;
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void setListViewParameters(ListView listView) {
		super.setListViewParameters(listView);
		listView.setDivider(null);
	}

	@Override
	public boolean handleRefreshLoadItem() {
		return super.handleRefreshLoadItem();

	}

	@Override
	protected void handleLoadNewItems(ATaskMark taskMark) {
		// 发送登录需要的参数
		HomePageTaskMark homePageTaskMark = (HomePageTaskMark) taskMark;
		PageInfo pageInfo = homePageTaskMark.getPageInfo();
		String version = DeviceUtil.getAppVersion(mContext);
		bModule.getServiceWrapper().homePage(this, homePageTaskMark, pageInfo.getNextFrom(), pageInfo.getSize(), version);
	}

	@Override
	protected void addListHeader(ListView listView) {
		super.addListHeader(listView);
		LinearLayout header = new LinearLayout(getContext());
		header.setOrientation(VERTICAL);
		// 加载轮播图view
		viewPageView = new HomepageCarouselView(activity, mInflater);
		header.addView(viewPageView.getCarouselView());

		// 加载9宫格
		mCategoryGridView = new HomepageCategoryGridView(mContext);
		header.addView(mCategoryGridView);

		mLiveFeedView = new HomepageLiveFeedView(mContext, mInflater);
		header.addView(mLiveFeedView.getLiveFeedView());

		//首页登录view及黄页view 注释2016 04 20
		//mNotLoginView = new HomepageNotLoginView(mContext, mInflater);
		//header.addView(mNotLoginView.getLoginOrRegisterView());
		//mAfterLoginView = new HomepageAfterLoginView(mContext, mInflater);
		//header.addView(mAfterLoginView.getAfterLoginView());
		//mBusinessView = new HomepageBusinessView(mContext, mInflater);
		//header.addView(mBusinessView.getBusinessView());

		header.addView(mInflater.inflate(R.layout.recommend_title, null));

		// 突发新闻
		mBreakNewsView = new HomepageBreakNewsView(activity, mInflater);
		header.addView(mBreakNewsView.getNewsView());

		listView.addHeaderView(header);
	}

	@Override
	protected void addListFooter(ListView listView) {
		super.addListFooter(listView);
		mFooterView = mInflater.inflate(R.layout.homepage_footer_view, null);
		listView.addFooterView(mFooterView);

		mFooterView.findViewById(R.id.news_list_button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				((MainActivity) mContext).showFragment(R.id.cityNewsTab, 0);
			}
		});
		mFooterView.findViewById(R.id.event_list_button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				((MainActivity) mContext).showFragment(R.id.eventTab, 0);
			}
		});
		mFooterView.setVisibility(GONE);
	}

	@Override
	public void notifyDataSetChanged() {
		updateHeaderView();
		super.notifyDataSetChanged();
	}

	private void updateHeaderView() {
//      首页登录view及黄页view 注释2016 04 20
//		BSharedPrefManager sharedPrefManager = ((MainApplication) imContext).getSharedPrefManager();
//		if (sharedPrefManager.getUserId() != null) {
//			mAfterLoginView.getAfterLoginView().setVisibility(View.VISIBLE);
//			mAfterLoginView.setViews();
//			mNotLoginView.getLoginOrRegisterView().setVisibility(View.GONE);
//		} else {
//			mNotLoginView.getLoginOrRegisterView().setVisibility(View.VISIBLE);
//			mAfterLoginView.getAfterLoginView().setVisibility(View.GONE);
//		}

		mBreakNewsView.initBreakNewsList();
		if (mBreakNewsView.getBreakNewsList() == null || mBreakNewsView.getBreakNewsList().size() == 0) {
			mBreakNewsView.getNewsView().setVisibility(View.GONE);
		} else {
			mBreakNewsView.getNewsView().setVisibility(View.VISIBLE);
			mBreakNewsView.setTopLineColor();
		}

		if (viewPageView != null) {
			viewPageView.initialize();
		}
		if (mCategoryGridView != null) {
			mCategoryGridView.init(bModule.getCacheManager().getHomeMenuInfoCache(), bModule.getCacheManager()
					.getDiscountCategoryInfoCache());
		}

		if (mLiveFeedView != null) {
			mLiveFeedView.init(bModule.getCacheManager().getHomeLiveFeedInfoCache());
		}

//		if (mBusinessView != null) {
//			mBusinessView.init(bModule.getCacheManager().getDiscountCategoryInfoCache());
//		}

		WeatherInfo weatherInfo = bModule.getCacheManager().getHomeWeatherInfoCache();
		if (mHomepageListener != null) {
			mHomepageListener.onWeatherInfoReceived(weatherInfo);
		}

	}

	@SuppressWarnings("rawtypes")
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		HomePageInfo info = (HomePageInfo) getAdapterView().getAdapter().getItem(position);
		if (info != null) {

			if (info.getRedirType() != null) {
				String redirType = info.getRedirType();
				Intent intent = null;
				if ("post".equals(redirType)) {
					intent = new Intent(getContext(), CityNewsDetailActivity.class);
					intent.putExtra("postId", info.getRedirPostId());
				} else if ("event".equals(redirType)) {
					intent = new Intent(getContext(), EventDetailActivity.class);
					intent.putExtra("postId", info.getRedirPostId());
				} else if ("business".equals(redirType)) {
					intent = new Intent(getContext(), CityDiscountDetailActivity.class);
					intent.putExtra("postId", info.getRedirPostId());
				} else if ("web".equals(redirType)) {
					intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(info.getRedirUrl()));
				} else if ("userpost_home".equals(redirType)) {
					intent = new Intent(getContext(), UserPostActivity.class);
				} else if ("userpost".equals(redirType)) {
					intent = new Intent(getContext(), UserPostDetailActivity.class);
					intent.putExtra(UserPostDetailActivity.POST_ID_EXTRA, info.getRedirPostId());
				} else if ("business_list".equals(redirType)) {
					if (bModule.getCacheManager().getDiscountCategoryInfoCache() != null &&
							bModule.getCacheManager().getDiscountCategoryInfoCache().size() >= 0) {
						intent = new Intent(getContext(), CityDiscoutResultActivity.class);
						intent.putExtra("index", getDiscountCategoryPosition(info.getRedirBusinessCategory(), bModule.getCacheManager().getDiscountCategoryInfoCache()));
						intent.putExtra("category", info.getRedirBusinessCategory());
						intent.putExtra("subcategory", info.getRedirBusinessSubcategory());
					} else {
						FetchCityDiscountsTaskMark aTaskMark = bModule.getTaskMarkPool()
								.getFetchCityDiscountsTaskMark();
						PageInfo pageInfo = aTaskMark.getPageInfo();
						String userId = "";
						UserInfo userInfo = bModule.getCacheManager().getUserInfo();
						if (userInfo != null) {
							userId = userInfo.getUserID();
						}
						bModule.getServiceWrapper().fetchCityDiscounts(this, aTaskMark, pageInfo.getNextFrom(),
								pageInfo.getSize(), userId, ((MainApplication) imContext).latitude, ((MainApplication) imContext).longitude);
					}
				}

				if (intent != null) {
					getContext().startActivity(intent);
				}

			} else {
				String postType = info.getPostType();
				Class cla = null;
				if ("post".equals(postType)) {
					cla = CityNewsDetailActivity.class;
				} else if ("event".equals(postType)) {
					cla = EventDetailActivity.class;
				} else if ("business".equals(postType)) {
					cla = CityDiscountDetailActivity.class;
				}
				if (cla != null) {
					Intent intent = new Intent(getContext(), cla);
					intent.putExtra("postId", info.getId());
					getContext().startActivity(intent);
				}
			}
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		return false;
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		super.receiveResult(taskMark, exception, trackerResult);

		if (taskMark instanceof FetchCityDiscountsTaskMark) {
			Intent intent = new Intent(getContext(), CityDiscoutResultActivity.class);
			intent.putExtra("index", 0);
			intent.putExtra("category", discountCategory);
			intent.putExtra("subcategory", discountSubcategory);
			getContext().startActivity(intent);
		}
	}

	public int getDiscountCategoryPosition(String category, List<DiscountCategoryInfo> discountCategoryInfoCache) {
		if (discountCategoryInfoCache == null) {
			return -1;
		}

		if (StringUtil.isEmptyString(category)) {
			return -1;
		}

		for (int index = 0, size = discountCategoryInfoCache.size(); index < size; index++) {
			if (category.equals(discountCategoryInfoCache.get(index).getName())) {
				return index;
			}
		}

		return -1;
	}

	@Override
	protected BaseAdapter createAdapter() {
		return new HomepageImportAdapter();
	}

	public class HomepageImportAdapter extends BaseAdapter {

		private Context mContext;
		private LayoutInflater lf;
		private int mDisplayedMaxPosition = -1;

		public HomepageImportAdapter() {
			this.lf = LayoutInflater.from(getContext());
			this.mContext = getContext();
		}

		@SuppressWarnings("unchecked")
		@Override
		public int getCount() {
			HashMap<String, Object> homePageMap = bModule.getCacheManager().getHomePageMap();
			if (homePageMap == null) {
				return 0;
			}
			List<HomePageInfo> homapageList = (List<HomePageInfo>) homePageMap.get(HomePageHandle.HOMEPAGE_MAP);
			if (homapageList != null && homapageList.size() > 0) {
				mTotalCount = homapageList.size();
				HomePageTaskMark homePageTaskMark = (HomePageTaskMark) mTaskMark;
				PageInfo pageInfo = homePageTaskMark.getPageInfo();
				int count = pageInfo.getFrom() + pageInfo.getSize();

				return count > mTotalCount ? mTotalCount : count;
			}

			return 0;
		}

		@SuppressWarnings("unchecked")
		@Override
		public HomePageInfo getItem(int position) {
			HashMap<String, Object> homePageMap = bModule.getCacheManager().getHomePageMap();
			List<HomePageInfo> homapageList = (List<HomePageInfo>) homePageMap.get(HomePageHandle.HOMEPAGE_MAP);
			if (homapageList != null && homapageList.size() > 0) {
				return homapageList.get(position);
			}

			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressWarnings("deprecation")
		@SuppressLint("NewApi")
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			ViewValueHand hand = null;
			View view = convertView;

			if (convertView == null) {
				view = lf.inflate(R.layout.import_list_view, parent, false);
				hand = new ViewValueHand(view);

				view.setTag(hand);
			} else {
				hand = (ViewValueHand) view.getTag();
			}

			HomePageInfo info = getItem(position);
			hand.title.setText(info.getPostsTitle());

			String postType = info.getPostType();
			if ("post".equals(postType)) {
				hand.badge.setText(info.getPostBadge() + "  " + getContext().getString(R.string.dot) + "  ");
			} else {
				hand.badge.setText(info.getPostBadge());
			}
//			if ("post".equals(postType)) {
//				hand.badge.setBackground(mContext.getResources().getDrawable(R.drawable.text_post_border));
//			} else if ("event".equals(postType)) {
//				hand.badge.setBackground(mContext.getResources().getDrawable(R.drawable.text_event_border));
//			} else if ("business".equals(postType)) {
//				hand.badge.setBackground(mContext.getResources().getDrawable(R.drawable.text_business_border));
//			}

			if (info.getPostAttachmentArray().isEmpty() || info.getPostAttachmentArray().size() < 3) {
				hand.imagesContainer.setVisibility(GONE);
				if (!StringUtil.isEmptyString(info.getPostAttachmentImage())) {
					hand.singleImage.setVisibility(VISIBLE);
					Picasso.with(getContext()).load(info.getPostAttachmentImage()).placeholder(R.drawable.no_image_placeholder)
							.resizeDimen(R.dimen.home_item_width, R.dimen.home_item_height).centerCrop()
							.into(hand.singleImage);
				} else {
					hand.singleImage.setVisibility(View.GONE);
				}
			} else {
				hand.singleImage.setVisibility(GONE);
				hand.imagesContainer.setVisibility(VISIBLE);
				for (int i = 0; i < 3; i++) {
					String imageUrl = info.getPostAttachmentArray().get(i);
					if (i == 0) {
						Picasso.with(getContext()).load(imageUrl).placeholder(R.drawable.no_image_placeholder)
								.resizeDimen(R.dimen.home_item_width, R.dimen.home_item_height).centerCrop()
								.into(hand.attachmentImageOne);
					} else if (i == 1) {
						Picasso.with(getContext()).load(imageUrl).placeholder(R.drawable.no_image_placeholder)
								.resizeDimen(R.dimen.home_item_width, R.dimen.home_item_height).centerCrop()
								.into(hand.attachmentImageTwo);
					} else if (i == 2) {
						Picasso.with(getContext()).load(imageUrl).placeholder(R.drawable.no_image_placeholder)
								.resizeDimen(R.dimen.home_item_width, R.dimen.home_item_height).centerCrop()
								.into(hand.attachmentImageThree);
					}
				}
			}

			if (!StringUtil.isEmptyString(info.getPdg())) {
				hand.date.setText(AppUtils.getDateStr(getContext(), info.getPdg()));
				hand.date.setVisibility(VISIBLE);
			} else {
				hand.date.setVisibility(GONE);
			}

			if (position == (getCount() - 1)) {
				tryQueryNewItems(true, ATaskMark.TYPE_DEFAULT);
			}

			if (position == mTotalCount - 1) {
				if (mFooterView != null) {
					mFooterView.setVisibility(VISIBLE);
				}
			}

			if (position > mDisplayedMaxPosition) {
				Animation fadeInAnimation = new AlphaAnimation(0, 1);
				fadeInAnimation.setDuration(1000);
				fadeInAnimation.setFillAfter(true);

				Animation translateAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
						Animation.RELATIVE_TO_SELF, 1,Animation.RELATIVE_TO_SELF, 0);
				translateAnimation.setDuration(1000);

				AnimationSet animationSet = new AnimationSet(true);
				animationSet.addAnimation(fadeInAnimation);
				animationSet.addAnimation(translateAnimation);

				hand.layout.startAnimation(animationSet);
				mDisplayedMaxPosition = position;
			}

			return view;
		}

		public class ViewValueHand {

			@Bind(R.id.layout)
			RelativeLayout layout;
			@Bind(R.id.title)
			TextView title;
			@Bind(R.id.post_attachment_img)
			ImageView singleImage;
			@Bind(R.id.attachment_imgs_container)
			LinearLayout imagesContainer;
			@Bind(R.id.post_attachment_img_one)
			ImageView attachmentImageOne;
			@Bind(R.id.post_attachment_img_two)
			ImageView attachmentImageTwo;
			@Bind(R.id.post_attachment_img_three)
			ImageView attachmentImageThree;
			@Bind(R.id.badge)
			TextView badge;
			@Bind(R.id.date)
			TextView date;

			public ViewValueHand(View view) {
				ButterKnife.bind(this, view);
			}
		}
	}

	private Spanned getReadDetailStyle(String content) {
		return Html.fromHtml(content + "..." + "<font color=\"#db6f51\">" + mContext.getString(R.string.read_detail)
				+ "</font>");
	}

	private String interceptPostContent(String content) {
		if (content.length() < 40)
			return content;
		return content.substring(0, 40);
	}

	public void updateHomePage() {
		updateHeaderView();
		notifyDataSetChanged();
	}

	public void sendActivityAndListener(Activity activity, HomepageListener listener) {
		this.activity = activity;
		this.mHomepageListener = listener;
	}

	public interface HomepageListener {
		void onWeatherInfoReceived(WeatherInfo weatherInfo);
	}
}